<template>
  <div>
    <!-- 头部导航 -->
    <van-nav-bar title="登录" />

    <!-- 表单 -->
    <van-form @submit="onSubmit">
      <van-field
        v-model="user.mobile"
        required
        name="mobile"
        label="手机号"
        placeholder="请输入11位手机号"
        :rules="[
          {
            required: true,
            message: '请填写正确的手机号',
            pattern: /^1[3-9]\d{9}$/,
          },
        ]"
      />
      <van-field
        v-model="user.code"
        required
        type="password"
        name="code"
        label="密码"
        placeholder="请输入6位密码"
        :rules="[
          { required: true, message: '请填写正确的密码', pattern: /^\d{6}$/ },
        ]"
      />

      <!-- 提交按钮 -->
      <div style="margin: 16px">
        <van-button
          round
          block
          type="info"
          native-type="submit"
          :disabled="isLoading"
          :loading="isLoading"
          loading-text="正在登录ing..."
        >
          提交
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { loginApi } from "@/api";
import { Notify } from "vant";
import { setToken } from "@/utils/token";
export default {
  name: "Login",
  data() {
    return {
      user: {
        mobile: "13888888888", //手机号
        code: "246810", //验证码(密码-必须是246810后台规定S的，)
      },
      isLoading: false, //登录按钮-加载状态
    };
  },
  methods: {
    async onSubmit(values) {
      // console.log("submit", values);
      // console.log(this.user);

      // 按钮加载状态设置-loading
      this.isLoading = true;

      try {
        const res = await loginApi(this.user);
        // console.log(res);
        Notify({ type: "success", message: "登录成功" });
        setToken(res.data.data.token);

        // 登录成功跳转一定写最后
        this.$router.replace({
          path: "/layout/home",
        });
      } catch (err) {
        Notify({ type: "danger", message: "账号或密码错误" });
      }

      // 网络请求成功或失败都把按钮加载状态关闭
      this.isLoading = false;
    },
  },
};
</script>

<style lang="less" scoped>
.van-nav-bar {
  background: #1989fa;

  /deep/.van-nav-bar__title {
    color: #fff;
  }
}
</style>